﻿using System.Windows.Input;
using Agnes.Core;
using System;

namespace Agnes.MyDocsLib
{
    /// <summary>
    /// 保存文档命令
    /// </summary>
    public class SaveDocCmd
    {
        private static SaveDocCmd _instance;

        /// <summary>
        /// 返回唯一实例
        /// </summary>
        public static SaveDocCmd Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new SaveDocCmd();
                }
                return _instance;
            }
        }

        private RoutedCommand _requery;

        /// <summary>
        /// 是否能执行
        /// </summary>
        public bool CanExcuted { get; set; }

        SaveDocCmd()
        {
            CanExcuted = false;
            _requery = new RoutedCommand("Article Save Cmd", typeof(SaveDocCmd));
        }

        /// <summary>
        /// 浏览文章的路由命令
        /// </summary>
        public static RoutedCommand Requery
        {
            get
            {
                return Instance._requery;
            }
        }

        /// <summary>
        /// 执行代码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void Excuted(object sender, ExecutedRoutedEventArgs e)
        {
            try
            {
                if (AgnesServiceManager.AgnesWorkBenchService.FocusedDocumentPanel != null)
                {
                    AgnesServiceManager.AgnesWorkBenchService.FocusedDocumentPanel.Save();
                }
            }
            catch (Exception ex)
            {
                AgnesServiceManager.LogServ.Error("MyDocsLib--保存文章失败，错误：" + ex.Message);
            }
        }

        /// <summary>
        /// 判断是否能执行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void CanExcute(object sender, CanExecuteRoutedEventArgs e)
        {
            if (AgnesServiceManager.AgnesSlnService.CurrentSln == null)
            {
                e.CanExecute = false;
            }
            else
            {
                if ((AgnesServiceManager.AgnesWorkBenchService.FocusedDocumentPanel != null))
                {
                    e.CanExecute = AgnesServiceManager.AgnesWorkBenchService.FocusedDocumentPanel.IsVaild 
                        && AgnesServiceManager.AgnesWorkBenchService.FocusedDocumentPanel.IsDirty;
                }
                else
                {
                    e.CanExecute = false;
                }
            }
        }
    }
}
